package net.piencak.phonetools.eurocoins;

import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.ImageItem;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.ItemCommandListener;
import javax.microedition.lcdui.ItemStateListener;

public class CoinForm extends Form {

	private EuroCoinCollector euroCoinCollectorMidlet;
	private ImageItem coinImageNational;
	private ImageItem coinImageCommon;
	private ChoiceGroup owned;
	
	int country = 0, coin = 0;

	private Wallet wallet;

	public CoinForm(EuroCoinCollector ecc) {
		super("Euro Coin Collector");

		euroCoinCollectorMidlet = ecc;
		setCommandListener(ecc);


		owned = new ChoiceGroup(null, ChoiceGroup.MULTIPLE);

		wallet = new Wallet();
		try {
		  wallet.load();
		} catch (Exception e) {
		  ecc.displayAlert("Chyba :(", "Zbierka sa nenačitala správne.\n" + e.getMessage(), 2000);
		}

		/*
		for (int i = 1; i < Gallery.COUNTRIES_COUNT; i++) {
			owned.append(Gallery.getCountryName(i), Gallery.getCoinImage(i, coin));
			owned.setSelectedIndex(0, wallet.isOwned(i, coin));
		}
		*/
		owned.append("v zbierke", null);
		owned.setSelectedIndex(0, wallet.isOwned(1, coin));
		append(owned);
		
		ItemStateListener listener = new ItemStateListener(){
		      public void itemStateChanged(Item item){
		    	  if (item == owned) {
		    		  wallet.setOwned(country, coin, owned.isSelected(0));
		    	  }
		      }
		    };
		setItemStateListener(listener);        
		setCoin(1, 0);
	}

	public void setCoin(int country, int coin) {
		if (coin != this.coin) {
			Gallery.cleanMem(coin);
		}
		this.country = country;
		this.coin = coin;
		String countryName = Gallery.getCountryName(country);
		setTitle(Gallery.COIN_NAME[coin] + " / " + countryName);
		if (coinImageNational == null) {
			coinImageNational = new ImageItem(null, Gallery.getCoinImage(
					country, coin), ImageItem.LAYOUT_DEFAULT, countryName);
			append(coinImageNational);
		} else {
			// this.coinImageNational.setLabel(Gallery.getCountryName(country));
			coinImageNational.setAltText(countryName);
			coinImageNational
					.setImage(Gallery.getCoinImage(country, coin));
		}

		if (coinImageCommon == null) {
			coinImageCommon = new ImageItem(null, Gallery.getCoinImage(0,
					coin), ImageItem.LAYOUT_DEFAULT, Gallery.getCountryName(0));
			append(coinImageCommon);
		} else {
			// this.coinImageNational.setLabel(Gallery.getCountryName(country));
			coinImageCommon.setAltText(Gallery.getCountryName(0));
			coinImageCommon.setImage(Gallery.getCoinImage(0, coin));
		}
		
		owned.setSelectedIndex(0, wallet.isOwned(country, coin));
	}

	public void save() {
		wallet.save();
	}
	
	public void destroy() {
		wallet.destroy();
	}
}
